<?php
/**
 * 第三方登陆
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-09-20
 * Time: 10:58
 */

namespace App\Http\Controllers\Api\V1\Front\User;


use App\Http\Controllers\Controller;
use App\Models\Account;
use App\Models\AccountInfo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class ThreeUserController extends Controller
{
    public function privilege(Request $request)
    {
        $data = $request->all();
        $validator = Validator::make($data, [
            'openId'        =>'required',
            'nickName'        =>'required',
            'avatar'        =>'required',
            'gender'        =>'required',
            'privilege'        =>'required',
        ]);
        if($validator->fails()){
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        $user = Account::select('t1.*','t2.*')
            ->from((new Account())->getTable().' as t1')
            ->leftJoin((new AccountInfo())->getTable().' as t2','t1.accountId','=','t2.accountId')
            ->where('openId',$data['openId'])
            ->first();
        if($user){//已经注册，直接返回信息
            return $this->apiResponse($user);
        }else{
            $result['userAccess'] = encrypt($data['openId'].time());
            $result['nickname'] = $data['nickName'];
            $result['avatar'] = $data['avatar'];
            $result['gender'] = $data['gender'];

            try{
                \DB::beginTransaction();
                $status = Account::create($result);
                if(!$status){
                    return $this->apiResponse('', config('errorCode.REGIST_FAILED'));
                }
                $data['accountId'] = $status['accountId'];
                unset($data['nickName']);
                unset($data['avatar']);
                unset($data['gender']);
                unset($data['privilege']);
                $status = AccountInfo::insert($data);
                if(!$status){
                    return $this->apiResponse('', config('errorCode.REGIST_FAILED'));
                }
                $user = Account::select('t1.*','t2.*')
                    ->from((new Account())->getTable().' as t1')
                    ->leftJoin((new AccountInfo())->getTable().' as t2','t1.accountId','=','t2.accountId')
                    ->where('openId',$data['openId'])
                    ->first();
                \DB::commit();
                return $this->apiResponse($user);
            }catch (\Exception $e){
                \DB::rollback();
                \Log::error("ThreeUserController privilege error.".$e->getMessage());
                return $this->apiResponse('', config('errorCode.REGIST_FAILED'));
            }
        }
    }
}